from django import forms

# from utils.ansible2.inventory import Inventory
# from utils.ansible2.runner import AdHocRunner
from . import models


class BaseFrom(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields.values():
            field.widget.attrs.update({"class": "form-control"})


class UserProfileForm(BaseFrom):
    class Meta:
        model = models.UserProfile
        fields = "__all__"

    def clean_email(self):
        email = self.cleaned_data['email']  # 来自于前端
        print(email)
        print(self.instance.email)
        users = models.UserProfile.objects.filter(email=email)
        if users.count() == 0:
            return email
        elif users.count() == 1 and email == self.instance.email:
            return email
        else:
            raise forms.ValidationError("邮箱已存在")


class HostForm(BaseFrom):
    class Meta:
        model = models.Host
        fields = "__all__"

    def clean_hostip(self):
        hostip = self.cleaned_data['hostip']
        host = models.Host.objects.filter(hostip=hostip)
        if host.count() == 0:  # 查不到值
            return hostip
        elif host.count() == 1 and hostip == self.instance.hostip:  # 查到了1条记录，并且host没有改变
            return hostip
        else:
            raise forms.ValidationError("ip地址已存在")

    # def isConnectionHost(self, host):
    #     host_data = [
    #         {
    #             "hostname": host,
    #             "ip": host,
    #             "port": 22
    #         },
    #     ]  # 主机列表
    #     inventory = Inventory(host_data)  # 动态生成主机配置信息
    #     runner = AdHocRunner(inventory)
    #     tasks = [
    #         {"action": {"module": "ping"}, "name": "run_whoami"},
    #     ]
    #
    #     # {'ok': {'192.168.244.150': {
    #     #     'run_whoami': {'invocation': {'module_args': {'data': 'pong'}}, 'ping': 'pong', '_ansible_parsed': True,
    #     #                    '_ansible_no_log': False, 'changed': False}}}, 'failed': {}, 'unreachable': {},
    #     #  'skipped': {}}
    #     ret = runner.run(tasks)
    #     if ret['ok']:
    #         return host
    #     else:
    #         raise forms.ValidationError("这个机器不在线")


class InitForm(BaseFrom):
    class Meta:
        model = models.Init
        # fields = "__all__"
        exclude = ['create_user']


class ProjectForm(BaseFrom):
    class Meta:
        model = models.Project
        fields = "__all__"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.fields["dev_user"].choices = [(u.pk, u.name) for u in models.UserProfile.objects.filter(role=0)]
        self.fields["test_user"].choices = [(u.pk, u.name) for u in models.UserProfile.objects.filter(role=1)]
        self.fields["ops_user"].choices = [(u.pk, u.name) for u in models.UserProfile.objects.filter(role=2)]


class InitLogForm(BaseFrom):
    class Meta:
        model = models.InitLog
        # fields = ['init', 'hosts_list']
        # fields = "__all__"
        fields = ["init", "hosts_list"]
        # exclude = ['create_user','create_time','result']
